import React, {Component} from 'react'
import {bindActionCreators} from 'redux'
import { connect } from 'react-redux'
import {setShowPrice, setSpecItem, setSpecData, setGoodsNum, shareLink, shareLogs, creatOrder, addToCard, setCollectStatus, collectGoods, cancelCollectGoods} from '../../../actions/detail/index'
import {getCarNum} from '../../../actions/headers/index'
import Router from 'next/router'
import Spec from './spec'

import {getCookie} from '../../../static/js/global'
import { basicConfig } from '../../../static/js/config'
import Coupon from './coupon'
var Stepper = require('antd-mobile/lib/stepper');
var Toast = require('antd-mobile/lib/toast');
var Popup = require('antd-mobile/lib/popup');
var _button = require('antd/lib/button');
var _icon = require('antd/lib/icon');
var Rate = require('antd/lib/rate');

class Index extends Component {
    constructor(){
        super();
        this.state = {
            buyLoading: false,
            cardLoading: false,
            collectNum: 0
        }
    }

    showToast(content,duration=2.5,cb=null,mask=true) {
        Toast.info(content, duration,cb,mask);
    }

    buyNow(){
        let specList = this.props.detail.detailData.specList;
        //有规格，必须选择
        if(specList && specList.length > 0) {
            if(!this.props.detail.specItem.specKey) {
                this.showToast("Please select the product specifications !");
                return false
            }
        }
        //数量大于0
        if(this.props.detail.goodsNum < 1) {
            this.showToast('Quantity must be greater than 0 !');
            return false
        }

        //切换按钮状态
        this.setState({buyLoading: true})

        /*item_id spec_key quantity*/

        this.props.creatOrder({
            itemId: Router.query.itemId,
            shopId: getCookie('shopId'),
            specId: this.props.detail.specItem.id || '0',
            quantity: this.props.detail.goodsNum,
            shareId: Router.query.shareId || ''
        })
            .then(res => {
                if (res.data.success) {
                    if(this.props.home.isFb) {
                        window.location.href = basicConfig.oldFbUrl + "/orders/order-confirm.html?groupId=" + res.data.data + '&shareId=' + (Router.query.shareId || '');
                        return false;
                    }
                    window.location.href = basicConfig.oldMobileUrl + '/trades/order-confirm.html?groupId=' + res.data.data + '&shareId=' + (Router.query.shareId || '');
                }
                else {
                    this.setState({buyLoading: false})
                }
            }).catch((error) => {
            this.setState({buyLoading: false})
        });
    }

    addToCart(){
        let specList = this.props.detail.detailData.specList;
        //有规格，必须选择
        if(specList && specList.length > 0) {
            if(!this.props.detail.specItem.specKey) {
                this.showToast("Please select the product specifications !");
                return false
            }
        }
        //数量大于0
        if(this.props.detail.goodsNum < 1) {
            this.showToast('Quantity must be greater than 0 !');
            return false
        }

        //切换按钮状态
        this.setState({cardLoading: true})

        /*item_id price spec_key quantity*/
        this.props.addToCard({
            itemId: Router.query.itemId,
            price: this.props.detail.showPrice.price,
            specId: this.props.detail.specItem.id || '0',
            quantity: this.props.detail.goodsNum,
            shareId: Router.query.shareId || ''
        })
            .then(res => {
                if (res.data.success) {
                    this.showToast('Add to cart successful !',1.5);
                    this.setState({cardLoading: false});
                    //更新购物车
                    this.props.getCarNum();
                }
                else {
                    this.setState({cardLoading: false})
                }
            }).catch((error) => {
            this.setState({cardLoading: false})
        });

    }

    handleCollect(action){
        if(action == 'add') {
            this.props.collectGoods({itemId: Router.query.itemId})
                .then(res=>{
                    if(res.data.success){
                        this.props.setCollectStatus(true);
                        this.setState({collectNum: this.state.collectNum + 1});
                    }
                }).catch((error) => {

                });
        }else {
            this.props.cancelCollectGoods({itemId: Router.query.itemId})
                .then(res=>{
                    if(res.data.success){
                        this.props.setCollectStatus(false);
                        this.setState({collectNum: this.state.collectNum - 1});
                    }
                }).catch((error) => {

                });
        }
    }

    shareCode(name,share='') {
        let data = this.props.detail.detailData;
        let sShareUrl = location.protocol+"//"+window.location.host+"/detail?itemId="+Router.query.itemId;;
        let sShareImg = data.image;
        let sShareContent = data.name;

        if(name == 'facebook') {
            document.getElementById("faceUrl").setAttribute("content",sShareUrl);
            document.getElementById("faceImg").setAttribute("content",sShareImg);
            document.getElementById("faceDes").setAttribute("content",sShareContent);
            document.getElementById("faceTit").setAttribute("content",sShareContent);
            if(share) {
                this.props.shareLink({channel: 'FACEBOOK', fissionId: data.fissionId})
                    .then(res => {
                        if (res.data.success) {
                            window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(res.data.data) + "&t=" + Math.random(), 'sharer', 'toolbar=0,status=0,width=626,height=436');
                        }
                    }).catch((error) => {
                        console.log('error: shareLink',error)
                    });
            }else{
                let url = location.protocol + "//" + window.location.host + "/api/marketing/channel/facebook/item/share?itemId=" + Router.query.itemId;
                this.props.shareLogs({channel: 'facebook', itemId: Router.query.itemId});
                window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+"&t="+Math.random(),'sharer','toolbar=0,status=0,width=626,height=436');
            }
        }
        if(name == 'twitter') {
            if(share) {
                this.props.shareLink({channel: 'TWITTER', fissionId: data.fissionId})
                    .then(res => {
                        if (res.data.success) {
                            window.open("http://twitter.com/home/?status=" + res.data.data, 'sharer', 'toolbar=0,status=0,width=626,height=436');
                        }
                    }).catch((error) => {
                        console.log('error: shareLink',error)
                    });
            }else{
                this.props.shareLogs({channel: 'twitter', itemId: Router.query.itemId});
                window.open("http://twitter.com/home/?status="+sShareUrl,'sharer','toolbar=0,status=0,width=626,height=436');
            }
        }
        if(name == 'pinterest') {
            if(share) {
                this.props.shareLink({channel: 'PINTEREST', fissionId: data.fissionId})
                    .then(res => {
                        if (res.data.success) {
                            window.open("https://www.pinterest.com/pin/create/extension/?spm=&url=" + encodeURIComponent(sShareUrl) + "&media=" + encodeURIComponent(res.data.data), 'sharer', 'toolbar=0,status=0,width=626,height=436');
                        }
                    }).catch((error) => {
                        console.log('error: shareLink',error)
                    });
            }else{
                this.props.shareLogs({channel: 'pinterest', itemId: Router.query.itemId});
                window.open("https://www.pinterest.com/pin/create/extension/?spm=&url=" + encodeURIComponent(sShareUrl) + "&media=" + encodeURIComponent(sShareImg),'sharer','toolbar=0,status=0,width=626,height=436');
            }
        }
    }
    showShareDiaolog(){
        this.props.shareLink({
            channel: 'SYSTEM',
            fissionId: this.props.detail.detailData.fissionId
        });
        const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
        let maskProps;
        if (isIPhone) {
            maskProps = {
                onTouchStart: e => e.preventDefault(),
            };
        }
        Popup.show(<div className="modal-share">
            <div className="modal-share-brokerage">
                <div className="modal-share-money"> GET US <span>${this.props.detail.detailData.brokerage}</span></div>
                <div className="modal-share-advertise">{this.props.detail.detailData.advertise}</div>
            </div>
            <ul className="">
                <li className="">
                    <span onClick={()=>{this.shareCode('facebook','share')}} className="social-sp social-facebook-icon"></span>
                    <p>Facebook</p>
                </li>
                <li className="">
                    <span onClick={()=>{this.shareCode('twitter','share')}} className="social-sp social-twitter-icon"></span>
                    <p>Twitter</p>
                </li>
                <li className="">
                    <span onClick={()=>{this.shareCode('pinterest','share')}} className="social-sp social-pinterest-icon"></span>
                    <p>Pinterest</p>
                </li>
            </ul>
            <div onClick={()=>{Popup.hide()}} className="cancel-btn">Cancel</div>
        </div>, { animationType: 'slide-up', maskProps, maskClosable: false });
    }

    handleGoodsNum(val){
        if(val > this.props.detail.specItem.inventory) {
            this.showToast('sorrry ,no enough inventory !',2);
            return false;
        }
        this.props.setGoodsNum(val)
    }

    render() {
        const { detail } = this.props;
        let data = detail.detailData;
        //价格
        let price = null;
        let ratePrice = null;
        ratePrice = <div className="do-price">
            <span><em>$</em>{detail.showPrice.price}</span>
            <span className="do-price-old"><em>$</em>{detail.showPrice.oldPrice}</span>
            <span className="do-price-discount">{`-${(1-detail.showPrice.rate).toFixed(2)*100}%`}</span>
        </div>;

        price = <div className="do-price">
            <span><em>$</em>{detail.showPrice.price}</span>
        </div>;


        //评分
        let score = 0;
        let avgscore = data.comment ? data.comment.avgscore : 0;
        if(avgscore > 0) {
            score = (avgscore%1) > 0.5 ? avgscore=Math.floor(avgscore) + 1 : (avgscore%1) > 0?Math.floor(avgscore) + 0.5:avgscore ;
            //score = avgscore >= Math.floor(avgscore) + 0.5 ? Math.floor(avgscore) + 0.5 : avgscore;
        }

        //分销
        let fenxiao = null;
        let shareDialog = null;
        if(data.brokerage > 0) {
            fenxiao = <_button onClick={()=>{this.showShareDiaolog()}} className="sub-btn" size='large'><i className="icon iconfont icon-dollor"></i> GET US ${data.brokerage}</_button>;
        }
        //无库存提示
        let tooltip = (detail.specItem.inventory || detail.specItem.inventory == null) ? null : <div className="out-tooltip"><_icon type="exclamation-circle-o"/> THIS PRODUCT IS NO LONGER IN STOCK !</div>;

        let btnDisable = detail.specItem.inventory > 0 ? false : true;

        //收藏
        let collectIcon = null;
        !this.props.detail.collectStatus ? collectIcon = <span onClick={()=>{this.handleCollect('add')}} className="add-wish"><_icon type="heart-o"/> Add to Wish List </span> : collectIcon = <span onClick={()=>{this.handleCollect('remove')}} className="add-wish"><_icon type="heart"/> collected </span> ;



        return(
            <div className="oprate-con">
                <h3 className="do-title">{data.name || ''}</h3>
                {detail.showPrice.rate != 1 ? ratePrice : price}
                <div className="star-list">
                    <Rate className="stars" disabled allowHalf value={score} />
                    <span className="comment-count">{`${data.comment ? data.comment.totalCount : 0} Reviews`}</span>
                </div>
                <Coupon couponList={data.couponList || []}></Coupon>
                <div className="oprate-line"></div>
                <Spec detail={detail || {}} setGoodsNum={this.props.setGoodsNum} setSpecData={this.props.setSpecData} setSpecItem={this.props.setSpecItem} setShowPrice={this.props.setShowPrice}></Spec>
                <div className="num-con">
                    <div className="num-name">NUMBER:</div>
                    <Stepper
                        style={{ width: '100%', minWidth: '2rem' }}
                        showNumber
                        max={detail.specItem.inventory || 1}
                        min={1}
                        value={detail.goodsNum}
                        useTouch={false}
                        onChange={(value)=>{this.handleGoodsNum(value)}}
                    />
                </div>
                {tooltip}
                <div className="btn-con">
                    <_button onClick={()=>{this.addToCart()}} loading={this.state.cardLoading} className="add-to-card" type="primary" size='large' disabled={btnDisable}><_icon type="shopping-cart"></_icon>ADD TO CART</_button>
                    {fenxiao}
                    <_button onClick={()=>{this.buyNow()}} loading={this.state.buyLoading} className="sub-btn" size='large' disabled={btnDisable}>BUY NOW</_button>
                </div>
                <div className="collect-con">
                    {collectIcon}<span className="adds-count"> ({`${this.state.collectNum + (data.collectCount || 0)} Adds`})</span>
                </div>
                <div className="oprate-line"></div>
                <div className="share-con">
                    <span onClick={()=>{this.shareCode('facebook')}} className="social-sp social-facebook-icon"></span>
                    <span onClick={()=>{this.shareCode('twitter')}} className="social-sp social-twitter-icon"></span>
                    <span onClick={()=>{this.shareCode('pinterest')}} className="social-sp social-pinterest-icon"></span>
                    <span className="paypal-icon right-icon"></span>
                    <span className="visa-icon right-icon"></span>
                </div>

            </div>

        )



    }
}

const mapStateToProps = ({
    detail,home
}) => ({
    detail,home
});

const mapDispatchToProps = (dispatch) => {
    return {
        setShowPrice: bindActionCreators(setShowPrice, dispatch),
        setSpecItem: bindActionCreators(setSpecItem, dispatch),
        setSpecData: bindActionCreators(setSpecData, dispatch),
        setGoodsNum: bindActionCreators(setGoodsNum, dispatch),
        shareLink: bindActionCreators(shareLink, dispatch),
        shareLogs: bindActionCreators(shareLogs, dispatch),
        creatOrder: bindActionCreators(creatOrder, dispatch),
        addToCard: bindActionCreators(addToCard, dispatch),
        setCollectStatus: bindActionCreators(setCollectStatus, dispatch),
        collectGoods: bindActionCreators(collectGoods, dispatch),
        cancelCollectGoods: bindActionCreators(cancelCollectGoods, dispatch),
        getCarNum: bindActionCreators(getCarNum, dispatch),
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Index)
